/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
namespace System.Qizx.Util
{
	
	/// <summary> Matches strings representing a path (with '/' separator) against a pattern
	/// which is a parent path.
	/// Can match direct children only, or any descendants.
	/// </summary>
	public class PathPrefixPattern:PrefixPattern
	{
		internal bool directChild;
		
		/// <param name="path">a normalized path using slashes
		/// </param>
		/// <param name="directChild">if true, matches only child paths
		/// </param>
		public PathPrefixPattern(string path, bool directChild):base(null, 0)
		{ // required
			this.directChild = directChild;
			if (!path.EndsWith("/"))
				path = path + "/";
			setPattern(path.ToCharArray(), path.Length);
		}
		
		public override bool matches(char[] string_Renamed)
		{
			// check length:
			int plen = _pattern.Length;
			if (string_Renamed.Length <= plen)
			// must be strictly longer
				return false;
			
			// start from the end: intentional, should be faster in general
			for (; --plen >= 0; )
				if (string_Renamed[plen] != _pattern[plen])
					return false;
			
			// if direct child, check there is no slash after:
			if (directChild)
			{
				plen = _pattern.Length;
				for (int i = string_Renamed.Length; --i >= plen; )
					if (string_Renamed[i] == '/')
						return false;
			}
			return true;
		}
		
		public override int match(char[] string_Renamed)
		{
			int plen = _pattern.Length;
			
			for (int i = 0, len = System.Math.Min(plen, string_Renamed.Length); i < len; i++)
			{
				int diff = string_Renamed[i] - _pattern[i];
				if (diff > 0)
					return BEYOND;
				if (diff != 0)
					return NOMATCH;
			}
			if (string_Renamed.Length <= plen)
				return NOMATCH;
			// prefix OK: check slash if child
			if (directChild)
			{
				plen = _pattern.Length;
				for (int i = string_Renamed.Length; --i >= plen; )
					if (string_Renamed[i] == '/')
						return NOMATCH;
			}
			return MATCH;
		}
	}
}